package com.pokermind.dse.tcp.client.interactive;

import com.pokermind.dse.tcp.protocol.ProtocolConstants;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 行动管理器 - 简化版
 * 
 * @author PokerMind Interactive Client
 */
public class ActionManager {
    
    private final TcpApiClient apiClient;
    
    public ActionManager(TcpApiClient apiClient) {
        this.apiClient = apiClient;
    }
    
    /**
     * 行动输入数据类
     */
    public static class ActionInput {
        private final String action;
        private final int amount;
        
        public ActionInput(String action, int amount) {
            this.action = action;
            this.amount = amount;
        }
        
        public String getAction() {
            return action;
        }
        
        public int getAmount() {
            return amount;
        }
    }
    
    /**
     * 请求AI决策（返回详细数据）
     */
    public Map<String, Object> requestAIAnalysis(GameState state, Player player) throws Exception {
        Map<String, Object> request = new HashMap<>();
        request.put("table_id", state.getTableId());
        request.put("hand_id", state.getHandId());
        request.put("player_id", player.getUserId());  // 修正：使用player_id
        request.put("position", player.getPosition());
        
        // 将底牌字符串转换为数组格式 "9s 8s" -> ["9s", "8s"]
        String holeCardsStr = player.getHoleCards();
        if (holeCardsStr != null && !holeCardsStr.isEmpty()) {
            java.util.List<String> holeCardsList = java.util.Arrays.asList(holeCardsStr.split(" "));
            request.put("hole_cards", holeCardsList);
        } else {
            request.put("hole_cards", new java.util.ArrayList<>());
        }
        
        // 打印格式化请求
        JsonFormatter.printRequest("AI分析", request);
        
        Map<String, Object> response = apiClient.sendRequest(
                ProtocolConstants.AI_ANALYZE_REQ,
                request
        );
        
        // 打印格式化响应
        JsonFormatter.printResponse("AI分析", response);
        
        Integer code = (Integer) response.get("code");
        if (code != null && code == 200) {
            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) response.get("data");
            return data;
        } else {
            throw new RuntimeException("AI分析失败: " + response.get("desc"));
        }
    }
    
    /**
     * 请求AI决策（简化版，返回ActionInput）
     */
    public ActionInput requestAIAction(GameState state, Player player) {
        try {
            Map<String, Object> data = requestAIAnalysis(state, player);
            
            if (data != null && data.containsKey("action")) {
                String action = (String) data.get("action");
                String sizeStr = (String) data.get("size");
                int amount = 0;
                
                if (sizeStr != null && !sizeStr.isEmpty()) {
                    try {
                        amount = Integer.parseInt(sizeStr);
                    } catch (NumberFormatException e) {
                        // 忽略
                    }
                }
                
                String reasons = (String) data.get("reasons");
                System.out.println("🤖 AI建议: " + action + (amount > 0 ? " " + amount : ""));
                if (reasons != null && !reasons.isEmpty()) {
                    System.out.println("   理由: " + reasons);
                }
                
                return new ActionInput(action, amount);
            }
            
            System.out.println("❌ AI未能给出有效建议");
            return null;
        } catch (Exception e) {
            System.out.println("❌ AI请求失败: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 记录玩家行动（别名方法，供InteractiveClient使用）
     */
    public boolean recordPlayerAction(GameState state, Player currentPlayer, String action, int amount) {
        return recordAction(state, currentPlayer, action, amount);
    }
    
    /**
     * 记录玩家行动
     */
    public boolean recordAction(GameState state, Player currentPlayer, String action, int amount) {
        if (action == null || action.isEmpty()) {
            System.out.println("❌ 行动类型为空");
            return false;
        }
        
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("table_id", state.getTableId());
            request.put("hand_id", state.getHandId());
            request.put("player_id", currentPlayer.getUserId());  // 修正：使用player_id
            request.put("action_type", action);  // 修正：使用action_type
            request.put("amount", amount);
            request.put("before_stack", currentPlayer.getStack());
            request.put("before_pot", state.getPot());
            
            // 打印格式化请求
            JsonFormatter.printRequest("记录行动", request);
            
            Map<String, Object> response = apiClient.sendRequest(
                    ProtocolConstants.RECORD_ACTION_REQ,
                    request
            );
            
            // 打印格式化响应
            JsonFormatter.printResponse("记录行动", response);
            
            Integer code = (Integer) response.get("code");
            if (code != null && code == 200) {
                // 更新本地状态
                @SuppressWarnings("unchecked")
                Map<String, Object> data = (Map<String, Object>) response.get("data");
                if (data != null) {
                    if (data.containsKey("after_stack")) {
                        currentPlayer.setStack((Integer) data.get("after_stack"));
                    }
                    if (data.containsKey("after_pot")) {
                        state.setPot((Integer) data.get("after_pot"));
                    }
                    if (data.containsKey("current_bet")) {
                        state.setCurrentBet((Integer) data.get("current_bet"));
                    }
                }
                
                // 更新玩家行动
                currentPlayer.setLastAction(action);
                currentPlayer.setLastActionAmount(amount);
                
                // 记录到历史
                state.addActionToHistory(currentPlayer.getUserId(), action, amount);
                
                System.out.println("行动记录成功: " + currentPlayer.getPosition() + " " + action + " " + amount);
                return true;
            } else {
                String desc = (String) response.get("desc");
                System.out.println("行动失败: " + desc);
                return false;
            }
        } catch (Exception e) {
            System.out.println("记录行动异常: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 完成手牌
     */
    public boolean completeHand(GameState state) {
        try {
            System.out.println("\n🏁 正在完成手牌...");
            
            Map<String, Object> request = new HashMap<>();
            request.put("table_id", state.getTableId());
            request.put("hand_id", state.getHandId());
            request.put("final_pot", state.getPot());
            
            // 找到赢家（剩余未弃牌的玩家）
            java.util.List<Player> activePlayers = state.getPlayers().stream()
                    .filter(Player::isInHand)
                    .toList();
            
            if (!activePlayers.isEmpty()) {
                request.put("winner_id", activePlayers.get(0).getUserId());
            }
            
            Map<String, Object> response = apiClient.sendRequest(
                    ProtocolConstants.COMPLETE_HAND_REQ,
                    request
            );
            
            Integer code = (Integer) response.get("code");
            if (code != null && code == 200) {
                state.markHandComplete();
                System.out.println("✅ 手牌完成成功");
                return true;
            } else {
                System.out.println("❌ 完成手牌失败: " + response.get("desc"));
                return false;
            }
        } catch (Exception e) {
            System.out.println("❌ 完成手牌异常: " + e.getMessage());
            return false;
        }
    }
}
